/**
 * 使用TS封装axios
 */

import axios, { type AxiosInstance, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import generateSign from '@/axios/sign'
import { Notice } from 'view-ui-plus'

interface IResponseData<T> {
  success: boolean
  object: T
  message: string | null
  errorCode: string | null
  result_code?: string
  debug_msg?: string
}

const service: AxiosInstance = axios.create({
	baseURL: '/',
	withCredentials: true,
	timeout: 20000
})

service.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
    if (config.url && config.url.startsWith('/q-plant')) {
      const { appId, sign, timestamp } = generateSign(JSON.parse(JSON.stringify(config)))
      const signParam = `app_id=${appId}&sign=${sign}&timestamp=${timestamp}&hash_type=md5`
      config.url = config.url.includes('?') ? `${config.url}&${signParam}` : `${config.url}?${signParam}`
    }
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

service.interceptors.response.use(
  (response: AxiosResponse<IResponseData<any>>) => {
    if (!response) {
      return Promise.reject('系统错误')
    }
    const { status, data, config } = response
    if (status === 200) {
      if (data.success === false) {
        const message = data.message || data.errorCode || '系统错误'
        Notice.error({
          title: '提示',
          desc: message
        })
        return Promise.reject(data)
      } else if (data.result_code === 'common_response_error') {
        let message = '系统错误'
        const debug_msg = data.debug_msg
        if (debug_msg) {
          if (debug_msg.includes('500:')) {
            try {
              const res = JSON.parse(debug_msg.substring(4))
              message = res.message || res.errorCode || '服务器内部错误'
            } catch (error) {
              
            }
          } else if (debug_msg.includes('502:')) {
            message = 'Interface 502'
          }
        }
        Notice.error({
          title: '提示',
          desc: message
        })
        return Promise.reject(response)
      } else {
        return Promise.resolve(response)
      }
    } else if (status === 404) {
      Notice.error({
        title: '提示',
        desc: '接口不存在'
      })
      return Promise.reject(response)
    } else {
      return Promise.reject(response)
    }
  }
)

export default service